<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Hash;
use App\Services\PasswordPolicyService;

class ChangePasswordRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        $passwordPolicy = app(PasswordPolicyService::class);
        
        return [
            'old_password' => 'required|string|max:255',
            'password' => ['required', 'string', 'confirmed', 'max:255', $passwordPolicy->getPasswordRules()],
        ];
    }

    /**
     * Get custom messages for validator errors.
     *
     * @return array
     */
    public function messages(): array
    {
        return [
            'old_password.required' => '原密码不能为空',
            'old_password.max' => '原密码长度不能超过255个字符',
            'password.required' => '新密码不能为空',
            'password.confirmed' => '两次输入的密码不一致',
            'password.min' => '新密码长度不能少于8位',
            'password.max' => '新密码长度不能超过255个字符',
        ];
    }

    /**
     * Configure the validator instance.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return void
     */
    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $user = auth()->user();
            
            if ($user && !Hash::check($this->old_password, $user->password)) {
                $validator->errors()->add('old_password', '原密码错误');
            }

            // 新密码不能与原密码相同
            if ($user && Hash::check($this->password, $user->password)) {
                $validator->errors()->add('password', '新密码不能与原密码相同');
            }
        });
    }
}

